﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Web.Services;
public partial class View_ManageSchedule : System.Web.UI.Page
{
    private ManageTimeTable mnTimeTable;
    private ManageBusStaion mnBusStation;
    private ManageBusTrip mnBusStrip;
    private ManageBusSchedule mnBusSchedule;
    private string SESSION_SEARCH = "SEARCH";
    private int maxOder;
    private int IDBusTrip;
    protected void Page_Load(object sender, EventArgs e)
    {
        mnBusStation = new ManageBusStaion();
        mnTimeTable = new ManageTimeTable();
        mnBusStrip = new ManageBusTrip();
        mnBusSchedule = new ManageBusSchedule();
        if (!IsPostBack)
        {
            Session.Remove(SESSION_SEARCH);
            dataDllDirection();
            dataDllBus();
            if (Request.QueryString["IDBusTrip"] != null && Request.QueryString["IDBusTrip"] != string.Empty)
            {
                String temp = Request.QueryString["IDBusTrip"];
                ddlNameBusTrip.SelectedValue = temp;
            }
        }
    }

    public void dataDllBus()
    {
        ddlNameBusTrip.Items.Clear();
        ddlNameBusTrip.DataSource = mnBusStrip.getAllBusTrip();
        ddlNameBusTrip.DataTextField = BusStripColumn.NameBusTrip;
        ddlNameBusTrip.DataValueField = BusStripColumn.IDBusTrip;
        ddlNameBusTrip.DataBind();
    }

    public void dataDllDirection()
    {
        List<ListItem> listItem = new List<ListItem>();
        listItem.Add(new ListItem("Chiều đi", "0"));
        listItem.Add(new ListItem("Chiều về", "1"));
        ddlDirection.DataSource = listItem;
        ddlDirection.DataBind();
    }

    /// <summary>
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgBusSchedule_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        if ((Session[SESSION_SEARCH] != null) && (Session[SESSION_SEARCH].ToString() != string.Empty))
        {
            rdgBusSchedule.DataSource = searchAllDataByIdBusAndDirection(Session[SESSION_SEARCH].ToString());
        }
        else
        {
            rdgBusSchedule.DataSource = getAllDataByIdBusAndDirection();
        }
        int id;
        id = int.TryParse(ddlNameBusTrip.SelectedValue, out id) ? id : 0;
        int direction = ddlDirection.SelectedIndex;
        String Direction = "Chiều đi";
        if (direction == 1)
        {
            Direction = "Chiều về";
        }
        maxOder = mnBusSchedule.getScheduleOrderMax(Direction, id);
    }

    public DataSet getAllDataByIdBusAndDirection()
    {
        int id;
        id = int.TryParse(ddlNameBusTrip.SelectedValue, out id) ? id : 0;
        int direction = ddlDirection.SelectedIndex;
        String Direction = "Chiều đi";
        if (direction == 1)
        {
             Direction = "Chiều về";
        }
        maxOder = mnBusSchedule.getScheduleOrderMax(Direction, id);
        return mnBusSchedule.getAllBusScheduleByDirectAndBus(Direction, id);
    }

    public DataSet searchAllDataByIdBusAndDirection(string search)
    {
        int id;
        id = int.TryParse(ddlNameBusTrip.SelectedValue, out id) ? id : 0;
        int direction = ddlDirection.SelectedIndex;
        String Direction = "Chiều đi";
        if (direction == 1)
        {
            Direction = "Chiều về";
        }
        maxOder = mnBusSchedule.getScheduleOrderMax(Direction, id);
        return mnBusSchedule.searchAllBusScheduleByDirectAndBus(Direction, id,search);
    }

    /// <summary>
    /// khuetd : Tim kiem ben do
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string stringSearch = txtKeyWord.Text.Trim();
        if (txtKeyWord.Text.Trim() == String.Empty)
        {
            stringSearch = hdfSearchString.Value.Trim();
        }

        if (Session[SESSION_SEARCH] != null)
        {
            if (hdfSearchString.Value.Trim() != Session[SESSION_SEARCH].ToString())
            {
                stringSearch = hdfSearchString.Value.Trim();
            }
            if (Session[SESSION_SEARCH].ToString() != txtKeyWord.Text.Trim())
            {
                stringSearch = txtKeyWord.Text.Trim();
            }
        }

        hdfSearchString.Value = stringSearch;
        rdgBusSchedule.DataSource = searchAllDataByIdBusAndDirection(stringSearch);
        rdgBusSchedule.Rebind();
        Session[SESSION_SEARCH] = stringSearch;
        txtKeyWord.Text = stringSearch;
    }

    /// <summary>
    /// ham do du lieu vao tung hang cua table
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgBusSchedule_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = e.Item as GridDataItem;
            string s = ((DataRowView)e.Item.DataItem)["OrderSchedule"].ToString();
            int oder;
            oder = int.TryParse(s, out oder) ? oder : 0;
            ImageButton Edit = ((ImageButton)item["Edit"].Controls[0]);
            Edit.CssClass = "btnEditDelete";
            Edit.Width = 20;
            Edit.Height = 20;
            Edit.Attributes.Add("style", "background-color:transparent");
            ImageButton Delete = ((ImageButton)item["Delete"].Controls[0]);
            Delete.CssClass = "btnEditDelete";
            Delete.Width = 20;
            Delete.Height = 20;
            Delete.Attributes.Add("style", "background-color:transparent;");
            if (oder < maxOder)
            {
                Edit.Visible = false;
                Delete.Visible = false;
            }
        }
        if (e.Item.IsInEditMode)
        {
            GridEditFormItem item = e.Item as GridEditFormItem;
            if (e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem)
            {
                Button btnAdd = new Button();
                btnAdd = item.FindControl("UpdateButton") as Button;
                btnAdd.Text = "Thêm mới";
                btnAdd.CssClass = "myButton";
                btnAdd.Attributes.Add("style", "margin-left:0px !important;");
                TextBox txtStationName = item.FindControl("txtStationName") as TextBox;
                String clientId = txtStationName.ClientID.ToString();
                txtStationNameHDF.Value = clientId;
                TextBox txtLongitude = item.FindControl("txtLongitude") as TextBox;
                txtLongitudehdf.Value = txtLongitude.ClientID.ToString();
                TextBox txtLatitude = item.FindControl("txtLatitude") as TextBox;
                txtLatitudehdf.Value = txtLatitude.ClientID.ToString();
              //  btnAdd.OnClientClick = "return checkAddNewClick();";
            }
            else
            {
                Button btnUpdate = new Button();
                btnUpdate = item.FindControl("UpdateButton") as Button;
                btnUpdate.Text = "Chỉnh sửa";
                btnUpdate.CssClass = "myButton";
                btnUpdate.Attributes.Add("style", "margin-left:0px !important;");
            }
            Button btnCancel = new Button();
            btnCancel = item.FindControl("CancelButton") as Button;
            btnCancel.Text = "Hủy bỏ";
            btnCancel.CssClass = "myButton";
            ImageButton hypelink = item.FindControl("HyperLinkMap") as ImageButton;
            hypelink.CssClass = "myHyperLink";
        }
    }
    protected void rdgBusSchedule_InsertCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
        BusStation station = new BusStation();
        TextBox txtStationName = editedItem.FindControl("txtStationName") as TextBox;
        TextBox txtLongitude = editedItem.FindControl("txtLongitude") as TextBox;
        TextBox txtLatitude = editedItem.FindControl("txtLatitude") as TextBox;

        station.StaionName = txtStationName.Text;
        station.Longitude = txtLongitude.Text;
        station.Latitude = txtLatitude.Text;

        if (String.IsNullOrEmpty(station.StaionName) || String.IsNullOrEmpty(station.Longitude) || String.IsNullOrEmpty(station.Latitude))
        {
            Message.Show(rapBusSchedule, "Chưa nhập dữ liệu", Message.Type.Error);
            return;
        }
        //lay ra id neu ben do ton tai roi hoac la chen vao neu chua ton tai
        int _result = mnBusStation.insertNewBusStaion(station);
        if (_result >= 1)
        {
            int id;
            id = int.TryParse(ddlNameBusTrip.SelectedValue, out id) ? id : 0;
            int direction = ddlDirection.SelectedIndex;
            String Direction = "Chiều đi";
            if (direction == 1)
            {
                Direction = "Chiều về";
            }
            int oder = mnBusSchedule.getScheduleOrderMax(Direction,id);
            BusSchedule schedule = new BusSchedule();
            schedule.IDBusTrip = id;
            schedule.IDStation = _result;
            schedule.OrderSchedule = oder + 1;
            schedule.Direction = Direction;

            int resultTemp = mnBusSchedule.insertNewBusSchedule(schedule);
            if (resultTemp > 0)
            {
                Message.Show(rapBusSchedule, "Thêm dữ liệu thành công!", Message.Type.Success);
            }
            else if (resultTemp == 0)
            {
                Message.Show(rapBusSchedule, "Đã tồn tại bến đỗ trong lịch trình : Lỗi hệ thống", Message.Type.Error);
            }
            else
            {
                Message.Show(rapBusSchedule, "Thêm không thành công : Lỗi hệ thống", Message.Type.Error);
            }
        }
        else
        {
            Message.Show(rapBusSchedule, "Thêm không thành công : Lỗi hệ thống", Message.Type.Error);
        }
        rdgBusSchedule.CurrentPageIndex = rdgBusSchedule.PageCount;
    }
    protected void rdgBusSchedule_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        int pageIndex = rdgBusSchedule.CurrentPageIndex;
        GridEditableItem editedItem = e.Item as GridEditableItem;
        int id;
        id = int.TryParse(editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BusScheduleColumn.IDSchedule].ToString(), out id) ? id : 0;

        TextBox txtStationName = editedItem.FindControl("txtStationName") as TextBox;
        TextBox txtLongitude = editedItem.FindControl("txtLongitude") as TextBox;
        TextBox txtLatitude = editedItem.FindControl("txtLatitude") as TextBox;
        BusStation station = new BusStation();
        station.StaionName = txtStationName.Text;
        station.Longitude = txtLongitude.Text;
        station.Latitude = txtLatitude.Text;

        if (String.IsNullOrEmpty(station.StaionName) || String.IsNullOrEmpty(station.Longitude) || String.IsNullOrEmpty(station.Latitude))
        {
            Message.Show(rapBusSchedule, "Chưa nhập dữ liệu", Message.Type.Error);
            return;
        }

        int _result = mnBusStation.insertNewBusStaion(station);
        if (_result > 1)
        {
            int temp = mnBusSchedule.updateBusSchedule(id,_result);
            if (temp == 1)
            {
                Message.Show(rapBusSchedule, "Chỉnh sửa dữ liệu thành công!", Message.Type.Success);
            }
            else if (temp == 0)
                Message.Show(rapBusSchedule, "Chỉnh sửa dữ liệu không thành công", Message.Type.Error);
            else
                Message.Show(rapBusSchedule, "Chỉnh sửa dữ liệu không thành công : Lỗi hệ thống", Message.Type.Error);
        }
        else if (_result == 0)
            Message.Show(rapBusSchedule, "Chỉnh sửa dữ liệu không thành công", Message.Type.Error);
        else
            Message.Show(rapBusSchedule, "Chỉnh sửa dữ liệu không thành công : Lỗi hệ thống", Message.Type.Error);
        rdgBusSchedule.CurrentPageIndex = pageIndex;
    }
    protected void rdgBusSchedule_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        int pageIndex = rdgBusSchedule.CurrentPageIndex;
        GridEditableItem editedItem = e.Item as GridEditableItem;
        BusStation station = new BusStation();
        int id;
        id = int.TryParse(editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BusScheduleColumn.IDSchedule].ToString(), out id) ? id : 0;

        int _result = mnBusSchedule.deleteBusSchedule(id);
        if (_result == 1)
            Message.Show(rapBusSchedule, "Xóa dữ liệu thành công!", Message.Type.Success);
        else if (_result == 0)
            Message.Show(rapBusSchedule, "Xóa dữ liệu không thành công", Message.Type.Error);
        else
            Message.Show(rapBusSchedule, "Xóa không thành công : Lỗi hệ thống", Message.Type.Error);
        rdgBusSchedule.CurrentPageIndex = pageIndex;
    }
    protected void ddlNameBusTrip_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        rdgBusSchedule.DataSource = getAllDataByIdBusAndDirection();
        rdgBusSchedule.Rebind();
    }
    protected void ddlDirection_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        rdgBusSchedule.DataSource = getAllDataByIdBusAndDirection();
        rdgBusSchedule.Rebind();
    }
}